package com.yonyou.gmmc.dealerApp.api.service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.marketing.common.constants.ResultMsgConstants;
import org.marketing.common.dto.askingPrice.AskingPriceDto;
import org.marketing.common.dto.customerInfo.CustomerBindCarsDto;
import org.marketing.common.dto.customerInfo.LoveModel4SaleDto;
import org.marketing.common.dto.customerInfo.PotentialUser4AfterSaleDto;
import org.marketing.common.dto.customerInfo.PotentialUser4SaleDto;
import org.marketing.common.dto.customerInfo.PuserOwnerRelationDto;
import org.marketing.common.dto.customerInfo.PuserUserCarOwnerRelationDto;
import org.marketing.common.dto.customerInfo.TlNormalFollowRecodeDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.SosHelpDto;
import org.marketing.common.dto.search.DealerAppSearchDto;
import org.marketing.common.dto.testdrivingAm.TestDrivingAmDto;
import org.marketing.common.exception.ServiceAppException;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.dealerApp.api.dao.TmPotentialUserMapper;
import com.yonyou.gmmc.dealerApp.api.entity.PuserOwnerRelationPO;
import com.yonyou.gmmc.dealerApp.api.entity.TlCarOwnerFollowRecodePO;
import com.yonyou.gmmc.dealerApp.api.entity.TlNormalFollowRecodePO;

/**
 * @author kaihua
 * 由于其他提供服务的微服务接口文档不完整，为了赶进度，目前所有实现放在本微服务自身中实现。
 * 后续有时间整理各个提供服务的微服务开放的功能接口之后，再通过调用其他微服务功能的方式调用功能
 *
 */
@Service
@Transactional
public class CustomerInfoService {
	private Logger  logger = Logger.getLogger(CustomerInfoService.class);
	
	@Autowired
	private TmPotentialUserMapper tmPotentialUserMapper;
	@Autowired
	private CallMaintainService callMaintainServiceInterface;
	@Autowired
	private CallTestDrivingService callTestDrivingServiceInterface;
//	@Autowired
//	private CallAskPriceService callAskPriceServiceInterface;

	/**
	 * 销售新增潜客检索
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getNotBindSales(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4SaleDto> list = tmPotentialUserMapper.getNotBindSales(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * DealerApp端潜在客户信息取得
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getPotentialUserList(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{
        List<PotentialUser4SaleDto> list = tmPotentialUserMapper.getNotBindSales(dealerAppSearchDto);
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 保存常规跟进记录
	 * @param tlNormalFollowRecodeDto
	 * @return
	 */
	public Map<String, Object> insertTlNormalFollowRecode(TlNormalFollowRecodeDto tlNormalFollowRecodeDto) {

		TlNormalFollowRecodePO tlNormalFollowRecodePO = new TlNormalFollowRecodePO();
        tlNormalFollowRecodePO.setCreateDate(new Date());
        BeanUtils.copyProperties(tlNormalFollowRecodeDto, tlNormalFollowRecodePO);
        tlNormalFollowRecodePO.setCreateBy(tlNormalFollowRecodeDto.getSalesConsultantId());
        tmPotentialUserMapper.insertTlNormalFollowRecode(tlNormalFollowRecodePO);
        tlNormalFollowRecodeDto.setNormalFollowRecodeId(tlNormalFollowRecodePO.getNormalFollowRecodeId());
        Map<String,Object> resultMap = new HashMap<String,Object>();
        if(tlNormalFollowRecodeDto!=null){
            resultMap.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
            resultMap.put("normalFollowRecodeId", tlNormalFollowRecodeDto.getNormalFollowRecodeId());
            resultMap.put(ResultMsgConstants.RESULT_MESSAGE,"");

        }
        return resultMap;
	}

	/**
	 * 删除心仪车型
	 * @param loveModel4SaleDto
	 * @return
	 */
	public Map<String, Object> deleteLoveModel(LoveModel4SaleDto loveModel4SaleDto) {
		Long result  = tmPotentialUserMapper.deleteLoveModel(loveModel4SaleDto.getLoveModelId());
        Map<String,Object> resultMap = new HashMap<String,Object>();
            resultMap.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
            resultMap.put(ResultMsgConstants.RESULT_MESSAGE,"");
            resultMap.put("loveModelId",result);
            return resultMap;
	}

	/**
	 * 保养到期提醒
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getMaintainWarning(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getMaintainWarning(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 保养到期提醒
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getInsuranceWarning(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getInsuranceWarning(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 客户信息取得
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getCustomerList(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = this.getCustomerListForSer(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}
	private List<PotentialUser4AfterSaleDto> getCustomerListForSer(DealerAppSearchDto dealerAppSearchDto) throws ServiceAppException,
    ServiceBizException {
		try {
            List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getCustomerList(dealerAppSearchDto);

            // 根据返回的结果集取得该潜客的试驾和询价信息
            if (null != list && !list.isEmpty()) {
                for (PotentialUser4AfterSaleDto pUser : list) {
                    // 绑定车型
                    List<CustomerBindCarsDto> bindCarsList = pUser.getBindCars();
                    if (!CheckUtil.NullOrEmpty(bindCarsList)){
                        CustomerBindCarsDto bind = bindCarsList.get(0);
                        pUser.setBindCarsInfo(bind.getLicenseNo()+"  "+"等多辆");
                    }
                    
                    if (!CheckUtil.NullOrEmpty(dealerAppSearchDto.getCustomerId())) {
                        // 把服务顾问清空
                        dealerAppSearchDto.setSalesConsultantId(null);
                        // 养修预约信息
                        Map<String, Object> resultMap = this.callMaintainServiceInterface.getMaintainInfoList(dealerAppSearchDto);

                        List<MaintainDto> maintainList = (List<MaintainDto>) resultMap.get("maintainList");
                        if (null != maintainList && !maintainList.isEmpty()) {
                            pUser.setMaintainCount(maintainList.size());

                        } else {
                            pUser.setMaintainCount(0);
                        }

                        // 一键救援
                        List<SosHelpDto> sosHelpList = this.callMaintainServiceInterface.getSosHelpInfoList(dealerAppSearchDto);
                        if (null != sosHelpList && !sosHelpList.isEmpty()) {
                            pUser.setSosHelpCount(sosHelpList.size());

                        } else {
                            pUser.setSosHelpCount(0);
                        }
                    } else {
                        // 如果客户ID为空，则绑定车辆、跟进记录和提醒消息为空，为一览信息内容。
                        pUser.setBindCars(null);
                        pUser.setFollowRecodelist(null);
                        pUser.setRemindMessage(null);
                    }

                }
                // 如果客户ID不为空，则只取得第一个。
                if (!CheckUtil.NullOrEmpty(dealerAppSearchDto.getCustomerId())) {
                    list = list.subList(0, 1);
                }
            }

            return list;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }
	}
	    
	/**
	 * 保存潜客和服务顾问关系表
	 * @param puserOwnerRelationDto
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> savePotentialSalesConsultant(PuserOwnerRelationDto puserOwnerRelationDto) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {

            Long userOwnerId = savePotentialSalesConsultantForSer(puserOwnerRelationDto);
            result.put("userOwnerId", userOwnerId);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
            result.put(ResultMsgConstants.RESULT_MESSAGE, "");
        } catch (Exception e) {
            result.put("userOwnerId", null);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
        }
        return result;
    }
	private Long savePotentialSalesConsultantForSer(PuserOwnerRelationDto puserOwnerRelationDto) throws ServiceAppException,
    ServiceBizException {
		this.logger.info(this.getClass().getName() + "savePotentialSalesConsultant BEGIN");
		try {
			PuserOwnerRelationPO puserOwnerRelationPO = new PuserOwnerRelationPO();
			BeanUtils.copyProperties(puserOwnerRelationDto, puserOwnerRelationPO);
			puserOwnerRelationPO.setCreateDate(new Date());
			puserOwnerRelationPO.setCreateBy(puserOwnerRelationDto.getUserId());
			Long result = tmPotentialUserMapper.savePotentialSalesConsultant(puserOwnerRelationPO);
			
			// 更新试乘试驾预约信息
			TestDrivingAmDto testDrivingAmDto = new TestDrivingAmDto();
			testDrivingAmDto.setDealerCode(puserOwnerRelationDto.getDealerCode());
			testDrivingAmDto.setPotentialUserId(puserOwnerRelationDto.getPotentialUserId());
			testDrivingAmDto.setSalesConsultantId(puserOwnerRelationDto.getUserId());
			callTestDrivingServiceInterface.updateTestdrivingAm4rush(testDrivingAmDto);
			
			// 更新购车询价信息
			AskingPriceDto askingPriceDto = new AskingPriceDto();
			askingPriceDto.setDealerCode(puserOwnerRelationDto.getDealerCode());
			askingPriceDto.setPotentialUserId(puserOwnerRelationDto.getPotentialUserId());
			askingPriceDto.setSalesConsultantId(puserOwnerRelationDto.getUserId());
//			callAskPriceServiceInterface.updateAskingPrice4rush(askingPriceDto);
			
			this.logger.info(this.getClass().getName() + "savePotentialSalesConsultant END");
			return result;
		} catch (Exception e) {
		logger.error(e.getMessage(), e);
		throw new ServiceAppException(e.getMessage(), e);
		}
	}
	/**
	 * 售后抢客户
	 * @param puserOwnerRelationDto
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> savePotentialSalesConsultant4AfterSales(PuserOwnerRelationDto puserOwnerRelationDto) throws Exception {
        Map<String, Object> result = new HashMap<String, Object>();
        try {
        	savePotentialSalesConsultant4AfterSalesForSer(puserOwnerRelationDto);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_SUCCESS);
            result.put(ResultMsgConstants.RESULT_MESSAGE, "");
        } catch (Exception e) {
            result.put("userOwnerId", null);
            result.put(ResultMsgConstants.RESULT_CODE, ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE, e.getMessage());
        }
        return result;
    }
	private void savePotentialSalesConsultant4AfterSalesForSer(PuserOwnerRelationDto puserOwnerRelationDto){
        this.logger.info(this.getClass().getName() + "savePotentialSalesConsultant4AfterSales BEGIN");
        try {
            List<PuserUserCarOwnerRelationDto> list = tmPotentialUserMapper.getPuserUserCarOwnerRelation(puserOwnerRelationDto.getPotentialUserId());
            if (!CheckUtil.NullOrEmpty(list)){
                for (PuserUserCarOwnerRelationDto pu :list){
                    puserOwnerRelationDto.setPotentialUserId(pu.getPotentialUserId());
                    PuserOwnerRelationPO puserOwnerRelationPO = new PuserOwnerRelationPO();
                    BeanUtils.copyProperties(puserOwnerRelationDto, puserOwnerRelationPO);
                    puserOwnerRelationPO.setCreateDate(new Date());
                    puserOwnerRelationPO.setCreateBy(puserOwnerRelationDto.getUserId());
                    tmPotentialUserMapper.savePotentialSalesConsultant(puserOwnerRelationPO);
                }
            }
            // 更新养修预约信息
            MaintainDto maintainDto = new MaintainDto();
            maintainDto.setDealerCode(puserOwnerRelationDto.getDealerCode());
            // 客户ID
            maintainDto.setUserId(puserOwnerRelationDto.getPotentialUserId().toString());
            // 服务顾问ID
            maintainDto.setSalesConsultantId(puserOwnerRelationDto.getUserId());
            this.callMaintainServiceInterface.updateMaintain4rush(maintainDto);
            
            // 更新一键救援信息
            SosHelpDto sosHelpDto = new SosHelpDto();
            
            sosHelpDto.setDealerCode(puserOwnerRelationDto.getDealerCode());
            // 客户ID
            sosHelpDto.setCarOwnerUserId(puserOwnerRelationDto.getPotentialUserId().toString());
            // 服务顾问ID
            sosHelpDto.setSalesConsultantId(puserOwnerRelationDto.getUserId());
            
            this.callMaintainServiceInterface.updateSosHelp4rush(sosHelpDto);
            
            this.logger.info(this.getClass().getName() + "savePotentialSalesConsultant4AfterSales END");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }
    }
	
	/**
	 * 售后未绑定销售顾问的潜在客户保养预约提醒检索
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getNotBindMaintainWarning(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getNotBindMaintainWarning(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 售后未绑定销售顾问的潜在客户保险预约提醒检索
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getNotBindInsuranceWarning(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getNotBindInsuranceWarning(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 售后新增潜客检索
	 * @param dealerAppSearchDto
	 * @return
	 */
	public Map<String, Object> getNotBindAfterSales(DealerAppSearchDto dealerAppSearchDto) {
		Map<String,Object> result = new HashMap<String,Object>();
        try{

        List<PotentialUser4AfterSaleDto> list = tmPotentialUserMapper.getNotBindAfterSales(dealerAppSearchDto);
 
        result.put("customerList", list);
        result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
        result.put(ResultMsgConstants.RESULT_MESSAGE,"");
        }catch(Exception e){
            result.put("customerList", null);
            result.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_ERROR);
            result.put(ResultMsgConstants.RESULT_MESSAGE,e.getMessage());
        }
        return result;
	}

	/**
	 * 保存潜客和服务顾问关系表
	 * @param puserOwnerRelationDto
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> rushSalesCustomer(PuserOwnerRelationDto puserOwnerRelationDto) throws Exception {
		return savePotentialSalesConsultant(puserOwnerRelationDto);
	}

	/**
	 * 售后抢客户
	 * @param puserOwnerRelationDto
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> rushAfterSalesCustomer(PuserOwnerRelationDto puserOwnerRelationDto) throws Exception {
		return savePotentialSalesConsultant4AfterSales(puserOwnerRelationDto);
	}

	/**
	 * 车主保存常规跟进记录
	 * @param tlNormalFollowRecodeDto
	 * @return
	 */
	public Map<String, Object> insertCarOwnerFollowRecode(TlNormalFollowRecodeDto tlNormalFollowRecodeDto) {
		tlNormalFollowRecodeDto = insertCarOwnerFollowRecodeForSer(tlNormalFollowRecodeDto);
        Map<String,Object> resultMap = new HashMap<String,Object>();
        if(tlNormalFollowRecodeDto!=null){
            resultMap.put(ResultMsgConstants.RESULT_CODE,ResultMsgConstants.RESULT_CODE_SUCCESS);
            resultMap.put("normalFollowRecodeId", tlNormalFollowRecodeDto.getNormalFollowRecodeId());
            resultMap.put(ResultMsgConstants.RESULT_MESSAGE,"");

        }
        return resultMap;
	}
	private TlNormalFollowRecodeDto insertCarOwnerFollowRecodeForSer(TlNormalFollowRecodeDto tlNormalFollowRecodeDto) throws ServiceAppException, ServiceBizException{
        try {
            TlCarOwnerFollowRecodePO tlCarOwnerFollowRecodePO = new TlCarOwnerFollowRecodePO();
            tlCarOwnerFollowRecodePO.setCreateDate(new Date());
            BeanUtils.copyProperties(tlNormalFollowRecodeDto, tlCarOwnerFollowRecodePO);
            tlCarOwnerFollowRecodePO.setCreateBy(tlNormalFollowRecodeDto.getSalesConsultantId());
            tlCarOwnerFollowRecodePO.setCarownerUserId(tlNormalFollowRecodeDto.getPotentialUserId());
            tmPotentialUserMapper.insertCarOwnerFollowRecode(tlCarOwnerFollowRecodePO);
            tlNormalFollowRecodeDto.setNormalFollowRecodeId(tlCarOwnerFollowRecodePO.getCarOwnerFollowRecodeId());

            return tlNormalFollowRecodeDto;
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            throw new ServiceAppException(e.getMessage(), e);
        }

    }
	
}
